#include <windows.h>
#include <FreeImage.h>
#include <string>
#include <vector>
#include <filesystem>
#include <algorithm>

using namespace std;
namespace fs = std::filesystem;

// Function to process and convert an image from inputPath to outputPath
void ProcessImage(const wstring& inputPath, const wstring& outputPath)
{
    // Convert wstring paths to string
    string inputPathStr(inputPath.begin(), inputPath.end());
    string outputPathStr(outputPath.begin(), outputPath.end());

    // Determine the image format
    FREE_IMAGE_FORMAT format = FreeImage_GetFileType(inputPathStr.c_str());
    if (format == FIF_UNKNOWN)
        format = FreeImage_GetFIFFromFilename(inputPathStr.c_str());

    // Load and save the image if it is JPEG or PNG
    if (format == FIF_JPEG || format == FIF_PNG)
    {
        FIBITMAP* bitmap = FreeImage_Load(format, inputPathStr.c_str());
        if (bitmap)
        {
            FreeImage_Save(FIF_BMP, bitmap, outputPathStr.c_str(), BMP_DEFAULT);
            FreeImage_Unload(bitmap);
        }
    }
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    PSTR szCmdLine, int iCmdShow)
{
    // Initialize FreeImage library
    FreeImage_Initialise();

    // List of supported extensions
    vector<wstring> extensions = { L".jpg", L".jpeg", L".png" };

    // Iterate through all files in the current directory
    for (const auto& entry : fs::directory_iterator(fs::current_path()))
    {
        if (entry.is_regular_file())
        {
            wstring ext = entry.path().extension().wstring();
            // Check if the file extension is supported
            if (find(extensions.begin(), extensions.end(), ext) != extensions.end())
            {
                wstring inputPath = entry.path().wstring();
                fs::path outputPath = entry.path();
                outputPath.replace_extension(L".bmp");
                // Process and convert the image
                ProcessImage(inputPath, outputPath.wstring());
            }
        }
    }

    // Deinitialize FreeImage library
    FreeImage_DeInitialise();
    return 0;
}